<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Rx.js," />










<meta name="description" content="前言这些笔记大部分都是阅读《深入浅出RxJS》一书的笔记。这是我第二次看了，第一次知识粗略的翻过，回想起来没有什么印象，所以决定再看一次。而这一次一边看一边做笔记，这样应该会印象更为深刻一点吧。 一、Rx.js 操作符——创建数据流在Rx.js中，有很多操作符，从哪开始学习是一个很让人纠结的问题。而数据流是一个非常重要的概念。并且在实际的开发中，数据流就是以Observable类的实例对象而存在的">
<meta name="keywords" content="Rx.js">
<meta property="og:type" content="article">
<meta property="og:title" content="Rx.js学习笔记（一）——创建数据流">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/11/02/Rx.js学习笔记（一）——创建数据流/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言这些笔记大部分都是阅读《深入浅出RxJS》一书的笔记。这是我第二次看了，第一次知识粗略的翻过，回想起来没有什么印象，所以决定再看一次。而这一次一边看一边做笔记，这样应该会印象更为深刻一点吧。 一、Rx.js 操作符——创建数据流在Rx.js中，有很多操作符，从哪开始学习是一个很让人纠结的问题。而数据流是一个非常重要的概念。并且在实际的开发中，数据流就是以Observable类的实例对象而存在的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-07T06:09:41.164Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Rx.js学习笔记（一）——创建数据流">
<meta name="twitter:description" content="前言这些笔记大部分都是阅读《深入浅出RxJS》一书的笔记。这是我第二次看了，第一次知识粗略的翻过，回想起来没有什么印象，所以决定再看一次。而这一次一边看一边做笔记，这样应该会印象更为深刻一点吧。 一、Rx.js 操作符——创建数据流在Rx.js中，有很多操作符，从哪开始学习是一个很让人纠结的问题。而数据流是一个非常重要的概念。并且在实际的开发中，数据流就是以Observable类的实例对象而存在的">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/11/02/Rx.js学习笔记（一）——创建数据流/"/>





  <title>Rx.js学习笔记（一）——创建数据流 | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/11/02/Rx.js学习笔记（一）——创建数据流/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Rx.js学习笔记（一）——创建数据流</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-02T00:11:47+08:00">
                2018-11-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Rx-js/" itemprop="url" rel="index">
                    <span itemprop="name">Rx.js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,522
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>这些笔记大部分都是阅读《深入浅出RxJS》一书的笔记。这是我第二次看了，第一次知识粗略的翻过，回想起来没有什么印象，所以决定再看一次。而这一次一边看一边做笔记，这样应该会印象更为深刻一点吧。</p>
<h3 id="一、Rx-js-操作符——创建数据流"><a href="#一、Rx-js-操作符——创建数据流" class="headerlink" title="一、Rx.js 操作符——创建数据流"></a>一、Rx.js 操作符——创建数据流</h3><p>在Rx.js中，有很多操作符，从哪开始学习是一个很让人纠结的问题。而数据流是一个非常重要的概念。并且在实际的开发中，数据流就是以Observable类的实例对象而存在的，因此学习Rx.js，从创建数据流开始是一个很好的开端。</p>
<p>总的来说，创建数据流的操作符有以下这些：</p>
<ul>
<li>create 直接创建数据流</li>
<li>of 根据有限的数据产生同步的数据流</li>
<li>range 产生一个数值范围内的数据</li>
<li>generate 以循环方式产生数据</li>
<li>repeat和repeatWhen 重复产生数据流中的数据</li>
<li>empty 产生空数据流</li>
<li>throw 产生直接出错的数据流</li>
<li>never 产生永不完结的数据流</li>
<li>interval和timer 间隔给定时间持续产生数据</li>
<li>from 从数组等枚举类型数据产生数据流</li>
<li>fromPromise 从Promise对象产生数据流</li>
<li>fromEvent和fromEventPattern 从外部事件对象产生数据流</li>
<li>ajax 从Ajax请求结果产生数据流</li>
<li>defer 延迟产生数据流</li>
</ul>
<h3 id="二、创建同步数据流"><a href="#二、创建同步数据流" class="headerlink" title="二、创建同步数据流"></a>二、创建同步数据流</h3><p>同步的数据流，顾名思义，就是产生的数据流其数据之间不存在时间间隔，因此我们无需考虑时间的问题。</p>
<h4 id="2-1-create"><a href="#2-1-create" class="headerlink" title="2.1 create"></a>2.1 create</h4><p>create算是最简单的一个操作符了，它的功能非常简单，就是直接调用Observable的构造函数，其主要的逻辑如下：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Observable.create = <span class="function"><span class="keyword">function</span>(<span class="params">subscribe</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Observable(subscribe)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的代码就在Observable类的定义之中，因此我们使用create无需导入其他模块就可以直接使用了。</p>
<p>也正是由于这个原因，它与直接使用Observable构造函数没啥区别，因此我在大多数情况用不上它的。</p>
<h4 id="2-2-public-static-of-values-…T-scheduler-Scheduler-Observable"><a href="#2-2-public-static-of-values-…T-scheduler-Scheduler-Observable" class="headerlink" title="2.2 public static of(values: …T, scheduler: Scheduler): Observable"></a>2.2 public static of(values: …T, scheduler: Scheduler): Observable<t></t></h4><p>我们可以利用of操作符可以创建指定个数据集合的Observable对象。比如我们要产生包含三个正整数的Observable对象，那么我们就可以这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; Observable &#125; <span class="keyword">from</span> <span class="string">'rxjs/Observable'</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">'rx.js/add/observable/of'</span></span><br><span class="line"><span class="keyword">const</span> source$ = Observable.of(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>)</span><br><span class="line">source$.subscribe(</span><br><span class="line">    <span class="built_in">console</span>.log,</span><br><span class="line">    <span class="literal">null</span>,</span><br><span class="line">    ()=&gt;<span class="built_in">console</span>.log(<span class="string">'complete'</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>按照上面的代码，source$可以产生Observable对象，再被subscribe后就可以把参数1,2,3吐出来了，然后调用Observer的complete函数。需要注意的是，它吐出的数据是同步的，没有任何时间间隔。</p>
<p>此外，if产生的是Cold Observable，因此对于每一个Obervable都会重复突出同样的一组数据，所以可以反复使用。</p>
<p>of适用的场景就是已知不多的几个数据，想要把这些数据用Observable对象来封装，而且无需时间间隔，我们就能用和这个来处理。</p>
<h4 id="2-3-range"><a href="#2-3-range" class="headerlink" title="2.3 range"></a>2.3 range</h4><p>range操作符顾名思义，就是能产生一个连续的数字序列。我们只需指定一个范围的开始值与长度：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> numbers = Rx.Observable.range(<span class="number">1</span>, <span class="number">100</span>)</span><br><span class="line">numbers.subscribe(<span class="function"><span class="params">x</span> =&gt;</span> <span class="built_in">console</span>.log(x))</span><br></pre></td></tr></table></figure>
<p>同样的，range产生的也是同步的数据，它会一次性的将数据给推出来。此外我们也可以让他是小数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> numbers = Rx.Observable.range(<span class="number">1.5</span>, <span class="number">100</span>)</span><br></pre></td></tr></table></figure>
<h4 id="2-4-generate"><a href="#2-4-generate" class="headerlink" title="2.4 generate"></a>2.4 generate</h4><p>generate类似一个for循环，我们可以设定一个初始值，每次递增这个值，知道满足每个条件的时候才会终止这个循环，循环体内可以根据值产生数据，比如我们想完成上面range的那个功能，我们就可以这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">const</span> range = <span class="function">(<span class="params">start, count</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> max = start + count</span><br><span class="line">    <span class="keyword">return</span> Observable.generate(</span><br><span class="line">    start, <span class="comment">// 初始值</span></span><br><span class="line">    value =&gt; value &lt; max, <span class="comment">// 条件语句</span></span><br><span class="line">    value =&gt; value + <span class="number">1</span>, <span class="comment">// 每次值的改变</span></span><br><span class="line">    value =&gt; value, <span class="comment">// 产生的结果</span></span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用generate中，四个参数分别对应了for循环中的不同表达式，除了第一个参数是一个值以外，其他三个参数都是函数，我们应该保持三个参数都是纯函数，这才不会与函数式编程的原则相违背。</p>
<p>此外，在generate产生不限于数值序列的数据流，字符串也是可以的:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source = Rx.Observable.gengerate(</span><br><span class="line">    <span class="string">'x'</span>,</span><br><span class="line">    value =&gt; value.length &lt;= <span class="number">3</span>,</span><br><span class="line">    value =&gt; value + <span class="string">'x'</span>,</span><br><span class="line">    value =&gt; value,</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>总的来说，在Rx.js中，我们在传统编程中用到for循环产生数据的情况，我们都可以使用generate来产生我们需要的数据流。</p>
<h4 id="2-5-repeat"><a href="#2-5-repeat" class="headerlink" title="2.5 repeat"></a>2.5 repeat</h4><p>repeat是一个实例操作符，它可以重复上游Observable中的数据若干次。比如我们想要重复的1,2,3的正整数序列10次，那么我们就能这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source$ = Observable.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="keyword">const</span> repeated$ = source$.repeat(<span class="number">10</span>)</span><br></pre></td></tr></table></figure>
<p>此外，repeat的重复功能依赖于上游的完结时机，所以，使用repeat很重要的就是要保证上游Observable对象最终一定会完结，那么repeat也就没有机会unsubscribe。其次，repeat的参数代表重复的次数，因此如果不传入这个参数，或者传入的参数是附属，就代表无限次的重复。</p>
<h4 id="2-6-empty"><a href="#2-6-empty" class="headerlink" title="2.6 empty"></a>2.6 empty</h4><p>empty代表一个直接完结的Observable对象，没有参数，不会残生任何数据，直接完结。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source = Rx.Observable.empty()</span><br></pre></td></tr></table></figure>
<h4 id="2-7-throw"><a href="#2-7-throw" class="headerlink" title="2.7 throw"></a>2.7 throw</h4><p>throw所产生的Observable对象也是啥都不做，直接出错，而抛出的错误就是throw的参数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source = Rx.Observable.throw(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'oops'</span>))</span><br></pre></td></tr></table></figure>
<h4 id="2-8-never"><a href="#2-8-never" class="headerlink" title="2.8 never"></a>2.8 never</h4><p>never操作符所产生的Observable对象真的啥都不做，即不突出数据，也不完结，也不会产生错误。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source = Rx.Observable.never()</span><br></pre></td></tr></table></figure>
<h3 id="三、创建异步数据流"><a href="#三、创建异步数据流" class="headerlink" title="三、创建异步数据流"></a>三、创建异步数据流</h3><p>异步数据流，或者说异步Observable对象，是Rx.js的解决问题的一大利器，上面的那些操作符所产生的都是同步的数据流，而处理异步操作就需要使用其他的操作符了。</p>
<h4 id="3-1-interval和timer"><a href="#3-1-interval和timer" class="headerlink" title="3.1 interval和timer"></a>3.1 interval和timer</h4><p>interval和timer这两个操作符的地位等同于JavaScript中的setInterval和setTimeout，但功能并不完全一样。</p>
<p>interval接受一个数值类型的参数，代表产生数据的间隔，返回的Observable对象就按照这个时间间隔从零开始输出递增的整数序列：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> number$ = Rx.Observable.interval(<span class="number">1000</span>)</span><br></pre></td></tr></table></figure>
<p>比如上面这条语句，它会从在1秒钟的时候突出数据0.然后再2秒钟的时候突出数据1…..需要注意的是，这个数据流是不会完结的，因为interval操作符不会主动调用下游的complete,要想停止这个数据序列，就必须要做退订的操作。</p>
<p>还有一个问题，interval本身所产生的异步数据序列只能从0开始递增，但实际中我们可以通过与其他操作符相结合来实现我们对其数据产生的定制化的需求：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source$ = Observable.interval(<span class="number">1000</span>)</span><br><span class="line"><span class="keyword">const</span> result$ = source$.map(x = x + <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>而timer则对于着setTimeout。time的第一个参数可以是一个数值，也可以是一个Date类型的对象。如果第一个参数是数值，代表的就是毫秒数，产生的Observable对象在指定毫秒之后会突出一个数据0，然后立即完结。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source$ = Rx.Observable.timer(<span class="number">1000</span>)</span><br></pre></td></tr></table></figure>
<p>上面这个功能同样也可以通过传递一个Date对象给timer来实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> now = <span class="keyword">new</span> <span class="built_in">Date</span>()</span><br><span class="line"><span class="keyword">const</span> later = <span class="keyword">new</span> <span class="built_in">Date</span>(now.getTime() + <span class="number">1000</span>)</span><br><span class="line"><span class="keyword">const</span> source$ = Observable.timer(later)</span><br></pre></td></tr></table></figure>
<p>但我们使用Date对象作为参数，要看情况而定。如果我们明确了需要延时产生数据的时间间隔，那就应该用数值作为参数，如果明确的是一个时间点，那么就传入Date对象。</p>
<p>timer还支持第二个参数，它决定了各数据之间的时间间隔。如果使用它，那么就会产生一个持续突出数据的Observable对象，类似interval的数据流：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source1$ = Rx.Obsevable.timer(<span class="number">2000</span>, <span class="number">1000</span>)</span><br><span class="line"><span class="keyword">const</span> source2$ = Rx.Obsevable.interval(<span class="number">2000</span>) <span class="comment">// source1$ 和 source2$ 所产生的数据流是一样的。</span></span><br></pre></td></tr></table></figure>
<h4 id="3-2-from"><a href="#3-2-from" class="headerlink" title="3.2 from"></a>3.2 from</h4><p>from可以说是创建类操作符中包容性最亲那个的一个了，因为它接受的参数只要像Observable就行了，然后就能根据参数中的数据阐述一个真正的Observable对象。比如以下这些：</p>
<ul>
<li>数组</li>
<li>字符串</li>
<li>Promise</li>
<li>generator</li>
<li>等等</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> source$ = Observable.from([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br></pre></td></tr></table></figure>
<h4 id="3-3-fromPromise"><a href="#3-3-fromPromise" class="headerlink" title="3.3 fromPromise"></a>3.3 fromPromise</h4><p>前面说的from操作符的参数可以使Promsie对象时，当这个Promsie成功结束时，from产生的Observable对象就会突出Promsie成功的结果，并且立即结束：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> promise = <span class="built_in">Promise</span>.resolve(<span class="string">'good'</span>)</span><br><span class="line"><span class="keyword">const</span> source$ = Observable.from(promise)</span><br><span class="line">source$.subscribe(</span><br><span class="line">    <span class="built_in">console</span>.log,</span><br><span class="line">    error = <span class="built_in">console</span>.log(<span class="string">'catch'</span>, error),</span><br><span class="line">    () =&gt; <span class="built_in">console</span>.log(<span class="string">'complete'</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>这种方式只有一个结果，所以当Promsie成功完成的时候，from也不知道不会再由新的数据了，所以立即完结了产生的Observable对象。</p>
<h4 id="3-4-fromEvent"><a href="#3-4-fromEvent" class="headerlink" title="3.4 fromEvent"></a>3.4 fromEvent</h4><p>fromEvent操作符在网页开发中最可能用到的操作符，以你为网页中总是要获取用户在网页中的操作时间，而fromEvent最常见的用法就是把DOM中的时间转化为Observable对象中的数据。</p>
<p>fromEvent接受两个参数，第一个参数是一个事件源，在浏览器中，最常见的事件源就是特定的DOM元素，第二个参数就是事件的名称，对于DOM事件就是click，mousemove这样的字符串。比如我们欧一段这样的HTML代码：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">'clickMe'</span>&gt;</span>Click Me<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">'text'</span>&gt;</span>0<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>当我们需要完成一个点击click时，下面的数字加一的需求时，我们就可以这样做：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> clickCount = <span class="number">0</span></span><br><span class="line"><span class="keyword">const</span> clickMe = doucment.querySelector(<span class="string">'#clickMe'</span>)</span><br><span class="line"><span class="keyword">const</span> text = doucment.querySelector(<span class="string">'#text'</span>)</span><br><span class="line"><span class="keyword">const</span> event$ = Rx.Observable.fromEvent(clickMe, <span class="string">'click'</span>)</span><br><span class="line">event$.subscribe(</span><br><span class="line">    () =&gt; &#123;</span><br><span class="line">        text.innerText = ++clickCount</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p> // 待续</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Rx-js/" rel="tag"># Rx.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/10/09/JavaScript函数式编程（一）/" rel="next" title="JavaScript函数式编程（一）">
                <i class="fa fa-chevron-left"></i> JavaScript函数式编程（一）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/11/05/three.js学习笔记（一）/" rel="prev" title="Three.js学习笔记（一）">
                Three.js学习笔记（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一、Rx-js-操作符——创建数据流"><span class="nav-number">2.</span> <span class="nav-text">一、Rx.js 操作符——创建数据流</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、创建同步数据流"><span class="nav-number">3.</span> <span class="nav-text">二、创建同步数据流</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-create"><span class="nav-number">3.1.</span> <span class="nav-text">2.1 create</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-public-static-of-values-…T-scheduler-Scheduler-Observable"><span class="nav-number">3.2.</span> <span class="nav-text">2.2 public static of(values: …T, scheduler: Scheduler): Observable</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-range"><span class="nav-number">3.3.</span> <span class="nav-text">2.3 range</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-generate"><span class="nav-number">3.4.</span> <span class="nav-text">2.4 generate</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-repeat"><span class="nav-number">3.5.</span> <span class="nav-text">2.5 repeat</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-6-empty"><span class="nav-number">3.6.</span> <span class="nav-text">2.6 empty</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-7-throw"><span class="nav-number">3.7.</span> <span class="nav-text">2.7 throw</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-8-never"><span class="nav-number">3.8.</span> <span class="nav-text">2.8 never</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、创建异步数据流"><span class="nav-number">4.</span> <span class="nav-text">三、创建异步数据流</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-interval和timer"><span class="nav-number">4.1.</span> <span class="nav-text">3.1 interval和timer</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-from"><span class="nav-number">4.2.</span> <span class="nav-text">3.2 from</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-fromPromise"><span class="nav-number">4.3.</span> <span class="nav-text">3.3 fromPromise</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-fromEvent"><span class="nav-number">4.4.</span> <span class="nav-text">3.4 fromEvent</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
